package com.csdig.cms.service.impl;

import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csdig.cms.dao.ChannelAttrDAO;
import com.csdig.cms.dao.ModelItemDAO;
import com.csdig.cms.model.ModelItem;
import com.csdig.cms.model.binder.ModelItemBinder;
import com.csdig.cms.service.CmsResourceMng;
import com.csdig.cms.service.ModelService;

@Service
@Transactional
public class ModelServiceImpl implements ModelService {

	@Autowired
	private CmsResourceMng resourceMng;

	@Autowired
	private ModelItemDAO modelItemDao;

	@Autowired
	private ChannelAttrDAO channelAttrDao;

	@Override
	public List<ModelItem> findModelItemByPath(String path) throws Exception {
		return modelItemDao.findbyPath(path);
	}

	@Override
	public void saveItems(String modelPath, String tplTxt, ModelItemBinder items) throws Exception {
		// 先判断channel中是否有引用
		List<ModelItem> modelItemList = items.getModelItems();

		for (ModelItem modelItem : modelItemList) {
			String field = modelItem.getField();
			if (StringUtils.isEmpty(field))
				continue;
			modelItem.setModelPath(modelPath);
			ModelItem oldRecord = modelItemDao.findUniqByCondi(modelPath, field);
			// 更新
			if (oldRecord != null) {
				modelItem.setModelItemId(oldRecord.getModelItemId());
				modelItemDao.update(modelItem);
			} else {
				modelItemDao.add(modelItem);
			}
		}

		// 删除 找出删除的item
		clearChannelAttr(modelPath);

		FileUtils.write(resourceMng.getFile(modelPath).getFile(), tplTxt, "utf-8");
	}

	public void clearChannelAttr(String modelPath) throws Exception {
		channelAttrDao.clearData(modelPath);
	}

}
